package Arraj;

import org.junit.Test;

import java.util.*;

/**
 * @BelongsProject: SeniorArchitect-LeetCode
 * @BelongsPackage: Arraj
 * @Author: zhuangiiaojan
 * @CreateTime: 2023-10-29  14:06
 * @Description: TODO
 * @Version: 1.0
 */
public class 数组中的kdiff数对532 {

    // 暴力解法
    public int findPairs(int[] nums, int k) {
        Set<Integer> visited = new HashSet<Integer>();
        Set<Integer> res = new HashSet<Integer>();
        for (int num : nums) {
            if (visited.contains(num - k)) {
                res.add(num - k);
            }
            if (visited.contains(num + k)) {
                res.add(num);
            }
            visited.add(num);
        }
        return res.size();
    }

    public int findPairs2(int[] nums, int k) {
        Arrays.sort(nums);
        int n = nums.length, j = 0, res = 0;
        for (int i = 0; i < n; i++) {
            if (i == 0 || nums[i] != nums[i - 1]) {
                while (j < n && (nums[j] < nums[i] + k || j <= i)) {
                    j++;
                }
                if (j < n && nums[j] == nums[i] + k) {
                    res++;
                }
            }
        }
        return res;
    }


    @Test
    public void test() {
        int pairs = findPairs(new int[]{3, 1, 4, 1, 5}, 2);
        System.out.println(pairs);
    }
}
